package com.kernel.streamDemo;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/****************************************
 * @name ZipInputStreamDemo
 * @description 解压缩文件
 * @author 黄彬恒
 * @since 2018/8/21
 ***************************************/
public class ZipInputStreamDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\ideaProgram\\IOLearning\\src\\main\\resources\\testDir\\test22.zip");// 实例化压缩文件对象
        File outFile;
        ZipFile zipFile = new ZipFile(file);
        ZipInputStream zipInput;
        OutputStream out;
        InputStream input;
        ZipEntry zipEntry;
        zipInput = new ZipInputStream(new FileInputStream(file));

        while ((zipEntry = zipInput.getNextEntry()) != null) {// 遍历压缩文件中的元素
            System.out.println("解压缩" + zipEntry.getName() + "文件");
            outFile = new File("D:\\ideaProgram\\IOLearning\\src\\main\\resources" + File.separator + zipEntry.getName());
            if (!outFile.getParentFile().exists()) {// 如果输出文件夹不存在
                outFile.getParentFile().mkdir();// 创建文件夹
            }
            if (!outFile.exists()) { // 判断输出文件是否存在
                outFile.createNewFile();// 创建文件
            }
            input = zipFile.getInputStream(zipEntry);// 得到压缩文件中每一个元素的输入流
            out = new FileOutputStream(outFile);
            int temp;
            while ((temp = input.read()) != -1) {// 边读边写
                out.write(temp);
            }
            input.close();
            out.close();
        }
        zipInput.close();
    }
}
